package com.demo.render;

import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;
import org.apache.velocity.VelocityContext;
import org.apache.velocity.app.Velocity;
import org.springframework.ui.freemarker.FreeMarkerTemplateUtils;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.StringWriter;
import java.util.*;

/**
 * @author liangliang
 */
public class HtmlUtil {

    /**
     * 渲染freemarker模板
     */
    public static String renderFreeMarker(Configuration freeMarkerConfiguration) {
        String txt = "";
        try {
            Template template = freeMarkerConfiguration.getTemplate("feedback.ftl");
            // 通过map传递动态数据
            Map<String, Object> map = new HashMap<String, Object>();
            map.put("demo", "demo");
            // 解析模板文件
            txt = FreeMarkerTemplateUtils.processTemplateIntoString(template, map);
            System.out.println("getText()->>>>>>>>>");
            System.out.println(txt);
            writeToFile(txt,"freemarker");
        } catch (IOException e) {
            // TODO 异常执行块！
            e.printStackTrace();
        } catch (TemplateException e) {
            // TODO 异常执行块！
            e.printStackTrace();
        }

        return txt;
    }

    /**
     * 渲染Velocity模板
     *
     * @return
     */
    public static String renderVelocity() {

        Properties p = new Properties();
        p.put("input.encoding", "UTF-8");
        p.put("output.encoding", "UTF-8");
        p.put("file.resource.loader.class", "org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader");
        Velocity.init(p);
        org.apache.velocity.Template template = Velocity.getTemplate("velocity/feedback.vm");
        VelocityContext context = new VelocityContext();
        StringWriter writer = new StringWriter();
        context.put("demo", "demo");
        List<String> pictures = new ArrayList<String>();
        pictures.add("http://pic2016.ytqmx.com:82/2017/0328/8/2.jpg%21960.jpg");
        pictures.add("http://pic2016.ytqmx.com:82/2017/0328/8/2.jpg%21960.jpg");
        pictures.add("http://pic2016.ytqmx.com:82/2017/0328/8/2.jpg%21960.jpg");
        context.put("pictures",pictures);
        template.merge(context, writer);
        System.out.println(writer.toString());
        writeToFile(writer.toString(),"velocity");
        return writer.toString();
    }

    private static void writeToFile(String str,String name) {
        FileWriter writer;
        File file  = new File("./out/");
        try {
            if(!file.exists()){
                 file.mkdir();
            }
            writer = new FileWriter("./out/"+name+".html");
            writer.write(str);
            writer.flush();
            writer.close();
        } catch (IOException e) {
            e.printStackTrace();

        }
    }
}
